#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>

static int ticket = 2000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* ThreadRoutine(void* args)
{
    std::string name = static_cast<const char*>(args);
    // std::string name = static_cast<std::string>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        if(ticket > 0)
        {
            std::cout << name << ":git ticket: " << ticket-- << std::endl;
        }
        else
        {
            std::cout << "ticket == 0" << std::endl;
            pthread_cond_wait(&cond, &mutex);
        }
        pthread_mutex_unlock(&mutex);
    }
}
int main()
{
    pthread_t tid1;
    pthread_create(&tid1, nullptr, ThreadRoutine, (void *)("thread_1")); // 难怪都是线程1，
    pthread_t tid2;
    // pthread_create(&tid2, nullptr, ThreadRoutine, (void *)("thread_1"));
    pthread_create(&tid2, nullptr, ThreadRoutine, (void *)("thread_2"));
    pthread_t tid3;
    // pthread_create(&tid2, nullptr, ThreadRoutine, (void *)("thread_1"));
    pthread_create(&tid3, nullptr, ThreadRoutine, (void *)("thread_3"));
    pthread_t tid4;
    // pthread_create(&tid2, nullptr, ThreadRoutine, (void *)("thread_1"));
    pthread_create(&tid4, nullptr, ThreadRoutine, (void *)("thread_4"));

    while(true)
    {
        sleep(2);
        pthread_mutex_lock(&mutex);
        ticket+=1000;
        // pthread_cond_signal(&cond); //每次都是同一个
        pthread_mutex_unlock(&mutex);
        pthread_cond_broadcast(&cond); //我觉得这个OS下是按阻塞队列的顺序发信号，

    }

    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);
    pthread_join(tid4, nullptr);
}